package com.treasure.mall.biz.service.core.user.impl;

import com.treasure.mall.biz.bo.config.SignConfig;
import com.treasure.mall.biz.dto.user.ModifyIntegralDTO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.entity.user.WxSubscribeUser;
import com.treasure.mall.biz.remote.wx.WxTemplateMessageService;
import com.treasure.mall.biz.repository.user.WxSubscribeUserRepository;
import com.treasure.mall.biz.service.core.BaseConfigService;
import com.treasure.mall.biz.service.core.marketing.UserSubscribeRedPacketService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.biz.service.core.user.WxSubscribeUserService;
import com.treasure.mall.zbq.common.ienum.integral.IntegralEnums;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * <p>
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.service.core.user.impl
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/8/26 8:50 下午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * 
 */
@Service
@Slf4j
public class WxSubscribeUserServiceImpl implements WxSubscribeUserService {

    @Autowired
    private WxSubscribeUserRepository repository;
    @Autowired
    private WxTemplateMessageService wxTemplateMessageService;
    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private UserService userService;
    @Autowired
    private UserSubscribeRedPacketService subscribeRedPacketService;

    @Override
    public void setSubscribeUser(WxMpUser wxMpUser, boolean subscribe) {
        this.setSubscribeUser(wxMpUser, subscribe, true);
    }

    /**
     * 设置用户关注
     *
     * @param wxMpUser              微信用户
     * @param subscribe             是否关注
     * @param isSendTemplateMessage 是否发送关注模板
     */
    @Override
    public void setSubscribeUser(WxMpUser wxMpUser, boolean subscribe, boolean isSendTemplateMessage) {
        try {
            //取消关注
            if (!subscribe) {
                unSubscribeUser(wxMpUser.getOpenId());
                return;
            }


            String unionId = "";
            UserPO userPO = null;
            WxSubscribeUser wxSubscribeUser = null;
            if (StringUtils.isNotBlank(wxMpUser.getUnionId())) {
                unionId = wxMpUser.getUnionId();
                userPO = userService.findByUnionId(unionId);
                wxSubscribeUser = repository.findFirstByUnionId(wxMpUser.getUnionId());
                if (wxSubscribeUser != null) {
                    wxSubscribeUser = setWxInfo(userPO, wxSubscribeUser);
                    wxSubscribeUser.setSubscribe(true);
                    repository.save(wxSubscribeUser);
                    if (isSendTemplateMessage) {
                        wxTemplateMessageService.sendSubscribeSuccessMessage(wxMpUser.getUnionId());
                    }
                    return;
                }
            }
            wxSubscribeUser = new WxSubscribeUser();
            wxSubscribeUser.setOpenId(wxMpUser.getOpenId());
            wxSubscribeUser.setSubscribe(true);
            wxSubscribeUser.setUnionId(unionId);
            wxSubscribeUser.setNickName(wxMpUser.getNickname());
            wxSubscribeUser = setWxInfo(userPO, wxSubscribeUser);
            repository.save(wxSubscribeUser);
            // 发送关注模板通知时
            if (isSendTemplateMessage) {

                if (userPO != null) {
                    //奖励关注红包
                    subscribeRedPacketService.setUserSubscribeAmount(userPO.getUserId());
                } else {
                    //发送关注模板消息
                    wxTemplateMessageService.sendSubscribeSuccessMessage(wxMpUser.getUnionId());
                }

                //得到签到获得积分的配置
                SignConfig config = baseConfigService.getSignConfig();

                // 添加关注奖励积分
                if (userPO != null && config.getSubscribeRewardIntegral() > 0) {
                    userService.modifyIntegral(
                            ModifyIntegralDTO.builder()
                                    .userId(userPO.getUserId())
                                    .integral(config.getSubscribeRewardIntegral())
                                    .logType(IntegralEnums.LogType.SUBSCRIBE)
                                    .build()
                    );
                }
            }
        } catch (Exception e) {
            log.error("setSubscribeUser", e);
        }
    }

    /**
     * 取消关注
     *
     * @param openId
     */
    private void unSubscribeUser(String openId) {
        WxSubscribeUser wxSubscribeUser = repository.findFirstByOpenId(openId);
        if (wxSubscribeUser != null && wxSubscribeUser.isSubscribe()) {
            wxSubscribeUser.setSubscribe(false);
            repository.save(wxSubscribeUser);
        }
    }


    private WxSubscribeUser setWxInfo(UserPO userPO, WxSubscribeUser wxSubscribeUser) {
        if (userPO != null) {
            wxSubscribeUser.setUserId(userPO.getUserId());
            wxSubscribeUser.setMobile(userPO.getMobile());
            wxSubscribeUser.setNickName(userPO.getNickName());
        }
        return wxSubscribeUser;
    }


    @Override
    public WxSubscribeUser findByUserId(Long userId) {
        UserPO userPO = userService.findById(userId);
        if (userPO == null || userPO.getWechatUser() == null || StringUtils.isEmpty(userPO.getWechatUser().getUnionId())) {
            return null;
        }
        return repository.findFirstByUnionId(userPO.getWechatUser().getUnionId());
    }

    @Override
    public WxSubscribeUser findByUnionId(String unionId) {
        return repository.findFirstByUnionId(unionId);
    }

    @Override
    public List<WxSubscribeUser> findAll() {
        return repository.findAll();
    }

    /**
     * 检查是否关注
     *
     * @param userId
     * @return
     */
    @Override
    public boolean checkSubscribe(Long userId) {
        WxSubscribeUser wxSubscribeUser = findByUserId(userId);
        return wxSubscribeUser != null && wxSubscribeUser.isSubscribe();
    }

    @Override
    public long count() {
        return repository.count();
    }

    @Override
    public long countBySubscribeIsTrue() {
        return repository.countBySubscribeIsTrue();
    }
}
